<?php

//Loader::loadClass('SecurityUtilEx', "modules/VoteMember/pnincludes");


/**
* smarty template auto call before render
*/
function _preRender(&$render){
  $lang    = FormUtil::getPassedValue ('lang', false , 'GET');
  $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');

  $render->assign ('_GET', $_GET);
  $render->assign ('_POST', $_POST);
  $render->assign ('_REQUEST', $_REQUEST);

  $render->assign('ctrl', $ctrl);
  //$render->assign('setting',InnoUtil::getSetting());
  $render->assign('service',   InnoUtil::getUserInfo());

  if ($lang){
    $render->assign('lang', $lang);
  }else{
    $render->assign('lang', pnUserGetLang());
  }
  $render->assign('access_edit', SecurityUtil::checkPermission('VoteMember::', '::', ACCESS_COMMENT));
}

/**
 * Main service function . the service side page controller
 * @author Chayakon PONGSIRI
 * @return string HTML string
 */
function VoteMember_service_main() {
    //_autoexecute();
    //return VoteMember_service_login();
    return VoteMember_service_login();
}

function VoteMember_service_login(){
      $uname      = FormUtil::getPassedValue ('uname');
      $pass       = FormUtil::getPassedValue ('pass');
       
      if( strlen(trim($uname)) > 0 && strlen(trim($pass)) > 0){
      //Check user in database
      
      $pntables = pnDBGetTables();
      $userColumn            = $pntables['users_column'];
      $groupPermissionColumn = $pntables['group_perms_column'];
      $groupMemberColumn     = $pntables['group_membership_column'];

      $userArray = array();

      $sql = "
              SELECT
                $pntables[users].$userColumn[uid],
                $pntables[users].$userColumn[uname],
                $pntables[users].$userColumn[pass],
                $pntables[users].$userColumn[email],
                $pntables[users].$userColumn[hash_method],
                $pntables[group_perms].$groupPermissionColumn[level]
              FROM
                $pntables[users],
                $pntables[group_perms],
                $pntables[group_membership]
              WHERE
                  $userColumn[uname] = '" . pnVarPrepForStore($uname) . "'
               AND
                  $pntables[users].$userColumn[uid] = $pntables[group_membership].$groupMemberColumn[uid]
               AND
                  $pntables[group_membership].$groupMemberColumn[gid] = $pntables[group_perms].$groupPermissionColumn[gid]
               ";
//echo $sql; exit;
        $column = array('uid', 'uname', 'pass', 'email', 'hash_method', 'level');

        $result = DBUtil::executeSQL($sql);
        $userArray = DBUtil::marshallObjects ($result, $column);

        //Check encryption type
        $hashArray = array('md5'=> 1, 'sha1'=> 5, 'sha256' => 8);
        $hash = array_search($userArray[0]['hash_method'], $hashArray); 
        $encryptPass = DataUtil::hash(strtolower($pass), $hash);

        //Check pass word
        if(isset($userArray) && !empty($userArray) && $userArray[0]['pass'] == $encryptPass){
/*
        //Query user layer
        $layerColumn            = $pntables['degis_layer_column'];
        $sql = "
                SELECT
                  $pntables[degis_layer].$layerColumn[id],
                  $pntables[degis_layer].$layerColumn[name],
                  $pntables[degis_layer].$layerColumn[country],
                  $pntables[degis_layer].$layerColumn[url]
                FROM
                  $pntables[users],
                  $pntables[degis_layer]
                WHERE
                    $pntables[users].$userColumn[uid] = $pntables[degis_layer].$layerColumn[uid]
                AND
                    $pntables[degis_layer].$layerColumn[uid] = ".$userArray[0]['uid']."
                ORDER BY $pntables[degis_layer].$layerColumn[id] ASC" ;

          $column = array('id', 'name', 'country', 'url');

          $result = DBUtil::executeSQL($sql);
          $layerArray = DBUtil::marshallObjects ($result, $column);
*/
          $response["uid"]   = $userArray[0]['uid'];
          $response["uname"] = $userArray[0]['uname'];
          $response["email"] = $userArray[0]['email'];
          $response["level"] = $userArray[0]['level'];
          //$response["url"]   = htmlentities($layerArray[0]['url']."?votename=".$layerArray[0]['name']."&country=".$layerArray[0]['country']."&filter=province");
          $response["errorCode"] = 0;
          $response["errorString"] = "ok";
          VoteMember_service_setResponse($response);
        } else{
          $response["errorCode"] = 1;
          $response["errorString"] = "user or password is wrong.";
          VoteMember_service_setResponse($response);
        }
      } else if( strlen(trim($uname)) > 0 ){
          $response["errorCode"] = 2;
          $response["errorString"] = "Please enter password.";
          VoteMember_service_setResponse($response);
      } else if( strlen(trim($pass)) > 0 ){
          $response["errorCode"] = 3;
          $response["errorString"] = "Please enter username.";
          VoteMember_service_setResponse($response);
      } else{
          $response["errorCode"] = 4;
          $response["errorString"] = "Please enter username and password ";
          VoteMember_service_setResponse($response);
      }
    }

function VoteMember_service_setResponse($response){

      //Gen xml
      $xml = new DOMDocument('1.0', 'UTF-8');
      $xml->formatOutput = true;

      $xml_node_response = $xml->createElement("response");
      $xml->appendChild( $xml_node_response );

      if($response["errorCode"] == 0){
        $xml_node_uid = $xml->createElement("uid",$response["uid"]);
        $xml_node_response->appendChild( $xml_node_uid );
        $xml_node_uname = $xml->createElement("uname",$response["uname"]);
        $xml_node_response->appendChild( $xml_node_uname );
        $xml_node_email = $xml->createElement("email",$response["email"]);
        $xml_node_response->appendChild( $xml_node_email );
        $xml_node_level = $xml->createElement("level",$response["level"]);
        $xml_node_response->appendChild( $xml_node_level );

        $xml_node_errorcode = $xml->createElement( "errorcode", $response["errorCode"]);
        $xml_node_response->appendChild( $xml_node_errorcode );
        $xml_node_errorstring = $xml->createElement( "errorstring", $response["errorString"]);
        $xml_node_response->appendChild( $xml_node_errorstring );

/*        $xml_node_layers = $xml->createElement("layers");
        $xml_node_response->appendChild( $xml_node_layers );
        foreach($response['layer'] as $val){
          $xml_node_layer = $xml->createElement("layer");
          $xml_node_layer->setAttribute("id", $val['id']);
          $xml_node_layers->appendChild( $xml_node_layer);
          $xml_node_type = $xml->createElement("type","layer");
          $xml_node_layer->appendChild( $xml_node_type);
          $xml_node_title = $xml->createElement("title",$val['name']);
          $xml_node_layer->appendChild( $xml_node_title);
          $xml_node_country = $xml->createElement("country",$val['country']);
          $xml_node_layer->appendChild( $xml_node_country);

          //$layer_title_link = urlencode(iconv( "ISO-8859-1","UTF-8", $val['name']));

          $xml_node_xml = $xml->createElement("xml", htmlentities($val['url']."?country=".$val['country']."&filter=province"));
          $xml_node_layer->appendChild( $xml_node_xml);
        }
*/
        //var_dump($response['layer']);
      }else{
        $xml_node_errorcode = $xml->createElement( "errorcode", $response["errorCode"]);
        $xml_node_response->appendChild( $xml_node_errorcode );
        $xml_node_errorstring = $xml->createElement( "errorstring", $response["errorString"]);
        $xml_node_response->appendChild( $xml_node_errorstring );
      }

      echo $xml->saveXML();
      pnShutDown();
    }




function VoteMember_service_autent() {
  //Cal with :: index.php?module=VoteMember&type=service&func=autent&uname=admin&pass=admin
  Loader::loadClass('LoginService', "modules/VoteMember/services");
  //Loader::loadClass('ProvinceService', "modules/VoteMember/services");  

  $uname      = FormUtil::getPassedValue ('uname');
  $pass       = FormUtil::getPassedValue ('pass');
	//var_dump($uname);var_dump($pass); exit;
  $user = new LoginService();
  
  if(isset($uname) && isset($pass)){
    $userArray = $user->validateUser($uname, $pass);
    if($userArray['validate'] == true){
    	//print_r($userArray);
    	
    	$accessArray = $user->getAccess($userArray['uid']);
    	$uid = $userArray['uid'];	
    	

    	//print_r($accessArray); exit;
  		
  		//Call service
 $request = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?module=VoteDataCenter&type=service&func=main&province=".$accessArray['province_access']."&district=".$accessArray['district_access']."&tambon=".$accessArray['tambon_access']."&uid=".$uid."&uname=".$uname;
  		//$request = "http://localhost/zk128" . "/index.php?module=VoteDataCenter&type=service&func=main&province=".$accessArray['province_access']."&district=".$accessArray['district_access']."&tambon=".$accessArray['tambon_access']."&uid=".$userArray['uid'];
  		//echo "request = ".$request; exit;
  		$response = @file_get_contents($request);
  		echo $response;
    	
    }else{
    
			echo '<?xml version="1.0" encoding="UTF-8"?>
						<datas>
							<data id=0>
								<title>User/Password is wrong.</title>
							</data>
						</datas>';  
    }
  }

  pnShutDown();

}


function VoteMember_service_access() {

  $uname      = FormUtil::getPassedValue ('uname');
  $pass       = FormUtil::getPassedValue ('pass');

  if(isset($uname) && isset($pass)){

    if(($uname=='nara')&&($pass=='12345'))
    {
      $request = "http://www.phuketinnova.com/demo/mba/index.php?module=VoteThailandPoll&type=xml&func=province&list=96";
      $response = @file_get_contents($request);
    }
    
    if(($uname=='demap')&&($pass=='demap'))
    {
      $request = "http://www.phuketinnova.com/demo/mba/index.php?module=VoteThailandPoll&type=xml&func=province&list=54";
      $response = @file_get_contents($request);
    }
     
    if($response === False){
        
        echo "  <?xml version='1.0' encoding='utf-8'?> 
                <datas> 
                  <data id='0'> 
                  </data> 
                <datas>";
    }else{
        
        print $response;
    }
  }
  pnShutDown();
}